# -*- coding: utf-8 -*-

import sys
import web
import itchat
import threading
from handle import Handle
from itchat.content import *

urls = (
    '/get99666', 'Handle',
    '/status', 'Status',
)

if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('utf8')

    # setup web server
    web_app = web.application(urls, globals())
    web_app.run()

    t = threading.Thread(target=web_app.run)
    t.setDaemon(True)
    t.setName('web-server')
    t.start()

    @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
    def text_reply(msg):
        msg.user.send('%s: %s' % (msg.type, msg.text))

    @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
    def download_files(msg):
        msg.download(msg.fileName)
        typeSymbol = {
            PICTURE: 'img',
            VIDEO: 'vid', }.get(msg.type, 'fil')
        return '@%s@%s' % (typeSymbol, msg.fileName)

    @itchat.msg_register(FRIENDS)
    def add_friend(msg):
        msg.user.verify()
        msg.user.send('Nice to meet you!')

    @itchat.msg_register(TEXT, isGroupChat=True)
    def text_reply(msg):
        if msg.isAt:
            msg.user.send(u'@%s\u2005I received: %s' % (
                msg.actualNickName, msg.text))

    itchat.auto_login(hotReload=True,
        statusStorageDir='itchat.pkl', 
        picDir='login_qr.jpg')
    itchat.run(True)
